#pragma once

#include <QObject>
#include <QUrl>
#include <QList>
#include <QMediaPlayer>
#include <QAudioOutput>
#include <QRandomGenerator>  // 随机数生成器

class QMediaPlaylist final : public QObject
{
    Q_OBJECT

public:
    enum PlaybackMode
    {
        CurrentItemOnce,
        CurrentItemInLoop,
        Sequential,
        Loop,
        Random
    };

    Q_ENUM(PlaybackMode)

    explicit QMediaPlaylist(QObject *parent = nullptr);

    // 基本功能
    PlaybackMode playbackMode() const;
    void setPlaybackMode(PlaybackMode mode);

    int currentIndex() const;
    QUrl currentMedia() const;
    int nextIndex(int steps = 1) const;
    int previousIndex(int steps = 1) const;

    int mediaCount() const;
    bool isEmpty() const;
    QUrl media(int index) const;

    // 列表操作
    void addMedia(const QUrl &content);
    void addMedia(const QList<QUrl> &items);
    bool insertMedia(int pos, const QUrl &content);
    bool insertMedia(int pos, const QList<QUrl> &items);
    bool removeMedia(int pos);
    bool removeMedia(int start, int end);
    void clear();

    // 播放控制
    void next();
    void previous();
    void setCurrentIndex(int playlistPosition);
    void shuffle();

    // 绑定到QMediaPlayer
    void bindPlayer(QMediaPlayer *player);

signals:
    void mediaInserted(int start, int end);
    void mediaRemoved(int start, int end);
    void mediaChanged(int start, int end);
    void currentIndexChanged(int position);
    void playbackModeChanged(PlaybackMode mode);
    void mediaAboutToBeInserted(int start, int end);
    void mediaAboutToBeRemoved(int start, int end);
    void currentMediaChanged(const QUrl &content);
    void loaded();
    void loadFailed();

private:
    int calculateNextPosition(int steps) const;
    int calculatePreviousPosition(int steps) const;

    QList<QUrl> m_playlist;
    int m_currentPos = -1;
    PlaybackMode m_playbackMode = Sequential;
    QMediaPlayer *m_player = nullptr;
};